package com.study.thread.demo.threadpool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义线程池
 *
 * @author wuxj
 */
public class ThreadPoolDemo extends ThreadPoolExecutor {

    /**
     * 当前执行总数
     */
    private AtomicInteger count = new AtomicInteger(0);
    /**
     * 起始时间
     */
    private long startTime = System.currentTimeMillis();

    /**
     * 本次任务执行总数
     */
    private volatile int totalCount;

    /**
     * 初始化线程池
     */
    public ThreadPoolDemo(Integer size, Long keepAliveTime, IgnorePolicyDemo ignorePolicyDemo) {
        super(size, size, keepAliveTime, TimeUnit.SECONDS, new ArrayBlockingQueue<>(20000), new TreadFactoryDemo(), ignorePolicyDemo);
    }

    @Override
    protected void beforeExecute(Thread t, Runnable r) {
        totalCount++;
    }

    /**
     * 线程执行花费时间
     *
     * @param r
     * @param t
     */
    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        int l = count.addAndGet(1);
        if (l == totalCount) {
            System.out.println("任务执行总时间:" + (System.currentTimeMillis() - startTime));
        }
    }
}
